package edu.nepu.bigdata.kafka;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import javax.tools.StandardJavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.JavaFileManager;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.lang.reflect.Method;
import java.util.Collections;

public class MainApp {
    public static void main(String[] args) {
        try {
            // 外部 Java 文件的路径
            String sourceFilePath = "ExternalClass.java";
            File sourceFile = new File(sourceFilePath);

            // 1. 编译 Java 文件
            compileJavaFile(sourceFilePath);

            // 2. 加载编译后的类
            URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(".").toURI().toURL()});
            String className = getClassNameFromFilePath(sourceFilePath);
            Class<?> clazz = classLoader.loadClass(className);

            // 3. 创建类的实例并调用方法
            Object instance = clazz.getDeclaredConstructor().newInstance();
            Method method = clazz.getMethod("execute");
            method.invoke(instance);

            // 清理生成的 .class 文件
            new File(className.replace('.', '/') + ".class").delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void compileJavaFile(String filePath) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            System.out.println("No Java compiler available.");
            return;
        }
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(new File(filePath));

        // 进行编译
        compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
        try {
            fileManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getClassNameFromFilePath(String filePath) {
        String fileName = new File(filePath).getName();
        return fileName.substring(0, fileName.lastIndexOf('.'));
    }
}






